package main

import (
	"crypto/md5"
	"encoding/hex"
	"fmt"
	"io/ioutil"
	"net/http"
	"net/url"
	"sort"
	"strings"
	"time"
)

var (
	appKey     = "26056555"
	appSecret  = "80010d73b703b59a0af5ecd56415665c"
	httpClient = &http.Client{
		Timeout: 4 * time.Second,
	}
)

func main() {
	//TbkItem()
	//TbkTpwd()
	//TbkUatmFavorites()
	tbkDgItemCoupon()
}

// 传 map 返回 key 排序
func sortMaptoKey(data map[string]interface{}) (arrSort []string) {
	arrSort = make([]string, len(data))
	i := 0
	for k := range data {
		arrSort[i] = k
		i++
	}
	sort.Strings(arrSort)
	return
}

// 生成sign
func createSign(param map[string]interface{}, sortKey []string) string {
	sign := appSecret
	for _, v := range sortKey {
		sign += fmt.Sprintf("%v%v", v, param[v])
	}
	sign += appSecret
	h := md5.New()
	h.Write([]byte(sign))
	return strings.ToUpper(hex.EncodeToString(h.Sum(nil)))
}

// url 参数拼接
func createStrParam(param map[string]interface{}) (strParam string) {
	strParam = ""
	for k, v := range param {
		strParam += (k + "=" + url.QueryEscape(fmt.Sprintf("%v", v)) + "&")
	}
	return
}

// 请求 淘宝
func TopApi(param map[string]interface{}) (string, error) {
	param["app_key"] = appKey
	param["v"] = "2.0"
	param["sign_method"] = "md5"
	param["format"] = "json"
	param["timestamp"] = time.Now().Format("2006-01-02 15:04:05")

	sign := createSign(param, sortMaptoKey(param))
	strParam := createStrParam(param)
	strParam += ("sign=" + sign)
	url := "https://eco.taobao.com/router/rest?" + strParam

	res, err := httpClient.Get(url)
	if err != nil {
		fmt.Println("请求出错")
		return "", err
	}
	defer res.Body.Close()

	bdata, err := ioutil.ReadAll(res.Body)
	if err != nil {
		fmt.Println("获取出错")
		return "", err
	}
	return string(bdata), nil
}
